package com.ctms.system.controller;

import com.ctms.system.domain.TaskReleaseDO;
import com.ctms.system.service.MailService;
import com.ctms.system.service.TaskReleaseService;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.thymeleaf.TemplateEngine;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Properties;

@RequestMapping("/mail")
@Controller
public class MailController {
    @Autowired
    JavaMailSender mailSender; //添加依赖后可以直接引用
    @Autowired
    TaskReleaseService taskReleaseService;

    // 注入常量,发件人邮箱
    @Value("${mail.fromMail.addr}")
    private String from;


    @PostMapping("/mailTask")
    @ResponseBody
    public String mailTask(String email,Integer tid){
        System.out.println("***********"+email);
        //任务详情
        TaskReleaseDO taskReleaseDO = taskReleaseService.selectTaskByTid(tid);
        //获取任务名
        String taskName = taskReleaseDO.getTaskTitle();
        //获取任务截至时间
        String end = taskReleaseDO.getTaskEndTime();
        String time = end.substring(0,16);
        JavaMailSenderImpl senderImpl = new JavaMailSenderImpl();
        // 设定mail server
        senderImpl.setHost("smtp.qq.com");
        senderImpl.setProtocol("smtp");
        senderImpl.setUsername(from);
        senderImpl.setPassword("outndtiawvitdabb");
        senderImpl.setPort(587);
        senderImpl.setDefaultEncoding("UTF-8");

        // 建立邮件消息
        SimpleMailMessage mailMessage = new SimpleMailMessage();
        // 设置收件人，寄件人 用数组发送多个邮件
        String array =email;
        mailMessage.setTo(array);
        mailMessage.setFrom(from);

        mailMessage.setSubject("实训作业未交提醒！");
        mailMessage.setText("请尽快提交实训作业："+taskName+"。"+"作业提交截止时间为："+time+"。");

        Properties prop = new Properties();
        prop.put("mail.smtp.auth", "true");
        prop.put("mail.smtp.timeout", "25000");
        senderImpl.setJavaMailProperties(prop);
        // 发送邮件
        senderImpl.send(mailMessage);
        System.out.println(" 邮件发送成功.. ");
        return "success";
    }


}
